//
//  DLDealRecordVC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/26.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLDealRecordVC.h"
#import "DLDealClassifyModel.h"
#import "DLDealListModel.h"
#import "DLDealBgScrollView.h"
#import "DLDealBgView.h"

@interface DLDealRecordVC ()<MSSegmentViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) NSArray *itemArr;

@property (nonatomic, strong) MSSegmentView *dealSegmentView;

@property (nonatomic, strong) DLDealBgScrollView *dealBgScrollView;

@property (nonatomic, strong) NSMutableArray *classifyListDataSource;

@property (nonatomic, strong) NSMutableArray *dealListDataSource;

@property (nonatomic, strong) NSMutableArray *loadedClassify;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger scrollViewPage;

@end

@implementation DLDealRecordVC

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initDataSource];
    [self setUpNav];
    [self loadClassifyData];
    [self layoutSubControls];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadNewDealData) name:@"DLreloadNewDealData" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMoreDealData) name:@"DLloadMoreDealData" object:nil];
}
- (void) reloadNewDealData {
    
    self.page = 1;
    DLDealClassifyModel *model = self.classifyListDataSource[self.scrollViewPage];
    NSLog(@"下拉刷新%@", model.name);
    [self loadDealListDataWithClassifyId:model.name];
}
- (void) loadMoreDealData {
    
    self.page++;
    DLDealClassifyModel *model = self.classifyListDataSource[self.scrollViewPage];
    NSLog(@"上拉加载%@", model.name);
    [self loadDealListDataWithClassifyId:model.name];
}
- (void) loadDealListDataWithClassifyId:(NSString *)classifyId {
    
    NSString *uniqueId = [DLKeyChainManager readUUID];
    if (isEmpty(uniqueId)) {
        uniqueId = [DLKeyChainManager createUUID];
        [DLKeyChainManager saveUUID:uniqueId];
    }
    
    NSString *postUrl = HTTPGetUserTradeRecord;
    NSDictionary *postDic = @{
//                              @"user_id" : kuserManager.isLogin?kuserManager.userInfoModel.userid:uniqueId,
                              @"classify" : classifyId,
                              @"pageNo" : @(self.page),
                              @"length" : @"10",
                              @"querytype" : classifyId
                              };
    [[DLNetWorkManager shareInstance] requestWithMethod:DLRequestMethodPOST path:postUrl parameters:postDic success:^(id  _Nonnull responseObject) {
        if (kRequestSuccess(responseObject)) {
            
            NSArray *arr = responseObject[@"result"];
            if (arr.count > 0) {
                if (self.page == 1) {
                    [self.dealListDataSource removeAllObjects];
                }
                for (NSDictionary *dic in arr) {
                    
                    DLDealListModel *dealListModel = [DLDealListModel mj_objectWithKeyValues:dic];
                    [self.dealListDataSource addObject:dealListModel];
                }
                
                self.dealBgScrollView.dealDataSource = self.dealListDataSource;
                
                [self.dealBgScrollView updateDealWithCurrentPage:self.scrollViewPage andDataSource:self.dealBgScrollView.dealDataSource];
                
            } else {
                if (self.page > 1) {
                    self.page--;
                }
            }
            
        } else {
            
            kShowRequestMsg(kSafeString(responseObject[@"message"]));
            if (self.page > 1) {
                self.page--;
            }
        }
        [self endAllRefresh];
    } failure:^(NSError * _Nonnull error) {
        NSLog(@"请求接口失败，错误是：%@", error);
        if (self.page > 1) {
            self.page--;
        }
        [self endAllRefresh];
    }];
}
- (void) endAllRefresh {
    [self.dealBgScrollView.dealView.dealTableView.mj_header endRefreshing];
    [self.dealBgScrollView.dealView.dealTableView.mj_footer endRefreshing];
}

- (void) loadClassifyData {
    
    for (NSInteger i = 0; i < self.itemArr.count; i++) {
        DLDealClassifyModel *classifyListModel = [DLDealClassifyModel new];
        classifyListModel.querytype = [NSString stringWithFormat:@"%ld", i + 1];
        
        NSDictionary *dic = self.itemArr[i];
        classifyListModel.name = dic[@"name"];
        
        [self.classifyListDataSource addObject:classifyListModel];
    }
}
- (void) layoutSubControls {
    MSSegmentView *dealSegmentView = [[MSSegmentView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, 48)];
    dealSegmentView.backgroundColor = [UIColor clearColor];
    dealSegmentView.textColor = kColorRGB(102, 102, 102);
    dealSegmentView.textSelColor = kDLBtnNormalBgColor;
    dealSegmentView.font = kBoldFont(14);
    dealSegmentView.selFont = kBoldFont(15);
    dealSegmentView.delegate = self;
//    dealSegmentView.layer.shadowColor = [UIColor grayColor].CGColor;
//    dealSegmentView.layer.shadowOpacity = 0.5f;
//    dealSegmentView.layer.shadowRadius = 4.f;
    
    dealSegmentView.lineColor = kDLBtnNormalBgColor;
    dealSegmentView.lineExWidth = 3;
    [self.view addSubview:dealSegmentView];
    self.dealSegmentView = dealSegmentView;
    
    self.dealSegmentView.itemTitles = self.itemArr;
    [self.dealSegmentView updateData];
    self.dealSegmentView.currentItemIndex = 0;
    
    DLDealBgScrollView *dealBgScrollView = [[DLDealBgScrollView alloc] initWithFrame:CGRectMake(0, kHeightNavigation, kScreenWidth, kScreenSafeAreaHeight - kHeightTabBar - kHeightNavigation)];
    dealBgScrollView.delegate = self;
    dealBgScrollView.pagingEnabled = YES;
    dealBgScrollView.backgroundColor = [UIColor whiteColor];
    dealBgScrollView.bounces = NO;
    dealBgScrollView.showsVerticalScrollIndicator = NO;
    dealBgScrollView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:dealBgScrollView];
    self.dealBgScrollView = dealBgScrollView;
    //配置scrollview
    dealBgScrollView.contentSize = CGSizeMake(kScreenWidth *self.itemArr.count, self.dealBgScrollView.height);
}

- (void) itemDidSelectedWithIndex:(NSInteger)index withCurrentIndex:(NSInteger)currentIndex {
    
    self.dealSegmentView.currentItemIndex = index;
    //#############
    DLDealClassifyModel *model = self.classifyListDataSource[index];
    NSString *currentClassiifyId = model.querytype;
    
    
    if (index == currentIndex) {
        
        NSLog(@"********当前停留的分类和点击的分类是一个，刷新数据");
        [self loadDealListDataWithClassifyId:currentClassiifyId];
    } else {
        
        if (![self.loadedClassify containsObject:currentClassiifyId]) {
            NSLog(@"********当前停留的分类和点击的分类不同，并且新点击的分类之前没点击过，要刷新数据");
            [self loadDealListDataWithClassifyId:currentClassiifyId];
        } else {
            NSLog(@"********当前停留的分类和点击的分类不同，并且新点击的分类之前已经加载过数据了");
        }
    }
    
    if (![self.loadedClassify containsObject:currentClassiifyId]) {
//        NSLog(@"********当前点击这个分类从来没点击过，这次点击了，要记录下来");
        [self.loadedClassify addObject:currentClassiifyId];
        
    }
    
    self.dealBgScrollView.contentOffset = CGPointMake(kScreenWidth * index, 0);
}

- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    NSInteger currentPage = (scrollView.contentOffset.x + kScreenWidth / 2) / kScreenWidth;
    DLDealClassifyModel *model = self.classifyListDataSource[currentPage];
    NSString *currentClassiifyId = model.querytype;
    if (![self.loadedClassify containsObject:currentClassiifyId]) {
        NSLog(@"^^^^^^^^当前停留页之前没滚动到过或者点击刷新过数据，要刷新数据");
        [self loadDealListDataWithClassifyId:currentClassiifyId];
    } else {
        NSLog(@"^^^^^^^^当前停留之前已经加载过数据了");
    }
    if (![self.loadedClassify containsObject:currentClassiifyId]) {
        NSLog(@"^^^^^^^^当前滚动到的这个分类从来没点击或滚动到过，这次滚动到了，要记录下来");
        [self.loadedClassify addObject:currentClassiifyId];
        
    }
}

- (void) scrollViewDidScroll:(UIScrollView *)scrollView {
    
    NSInteger currentPage = (scrollView.contentOffset.x + kScreenWidth / 2) / kScreenWidth;
    self.dealSegmentView.currentItemIndex = currentPage;
    
    self.scrollViewPage = currentPage;
}
- (void) setUpNav {
    self.titleView.title = @"交易记录";
}
- (void) initDataSource {
    NSArray *itemArr = @[@{@"name" : @"全部"}, @{@"name" : @"购买"}, @{@"name" : @"赎回"}, @{@"name" : @"调仓"}];
    self.itemArr = itemArr;
    
    self.classifyListDataSource = [NSMutableArray array];
    self.dealListDataSource = [NSMutableArray array];
    self.loadedClassify = [NSMutableArray array];
    self.page = 1;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
